#!/bin/bash
#SBATCH --nodes=1
#SBATCH --partition=wzhdtest
#SBATCH --ntasks-per-node=32
#SBATCH --time=24:00:00
#SBATCH --job-name=prepare_ligands
#SBATCH -e log/prepare_ligands-%j.out
#SBATCH -o log/prepare_ligands-%j.out

source ~/.bashrc
source /work/home/aixplorerbio_wz/miniconda3/bin/activate amber
source /work/home/aixplorerbio_wz/software/gromacs-2020.3/bin/GMXRC

module switch compiler/dtk/21.10
module load apps/Gromacs-DCU2/2020.3/hpcx-gcc-7.3.1

if [ $# != 1 ]; then
    echo "USAGE: $0 $PROJECT_HOME"
    echo " e.g.: $0 ../"
    exit 1
fi

pwd=$(pwd)
PROJECT_HOME=$(cd $1 && pwd)
LIGANDS_PATH=$PROJECT_HOME/ligands
WORK_PATH=$PROJECT_HOME/work_dir
MD_PATH=$WORK_PATH/md

echo "PROJECT_HOME=$PROJECT_HOME ..  "

rm -rf $MD_PATH
mkdir -p $MD_PATH

if [ ! -d "$LIGANDS_PATH" ]; then
    echo "directory \"$LIGANDS_PATH\" not exists"
    exit 1
fi

if [ ! -d "$WORK_PATH/sdf" ]; then
    echo "directory \"$$WORK_PATH/sdf\" not exists"
    exit 1
fi

cd $WORK_PATH/sdf
lig_name=$(ls *.sdf)

function get_itp {
    lig_f=$1
    lig_dir_f=$2
    obabel $lig_f -O ${lig_dir_f}_h.sdf -h
    python $LIGANDS_PATH/get_net_charge.py -mol_file ${lig_dir_f}_h.sdf
    charge=$(cat charge.dat)
    acpype -i ${lig_dir_f}.mol -b MOL -a gaff2 -n $charge -c bcc -f
}

for lig in $lig_name; do
    lig_dir=${lig%%.*}
    md_dir=$MD_PATH/$lig_dir
    mkdir -p $md_dir
    echo "into $md_dir .."
    cp $lig $md_dir
    cd $md_dir
    # cp ../*.py ./
    get_itp $lig $md_dir/$lig_dir &
    #python cat_gmx_top.py
    cd -
done
wait

cd $pwd
echo "finish getting ligands itp"
